#include "timer.h" 
#include "speed_reading.h"
#include "M2M_Serial_Console.h"
#include "M2P_Serial_Console.h"
#include "USART2_DMA.h"
#include "USART1_DMA.h"
#include "led.h" //通用定时器 3中断初始化
//这里时钟选择为 APB1的 2倍，而 APB1为 36M //arr：自动重装值。
//psc：时钟预分频数
//这里使用的是定时器 3! 

unsigned char TIM3Control;
unsigned char TIM3Flag;
u16 System_Time_Counter=0;
u16 Fast_Routine=200;
u16 Slow_Routine=500;
u16 System_Routine=1000;
u16 PWM_Routine=15;

void TIM6_init(u16 arr,u16 psc) 
{ 
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; 
    NVIC_InitTypeDef NVIC_InitStructure; 
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM6, ENABLE); //①时钟 TIM3使能
    //定时器 TIM3初始化
    TIM_TimeBaseStructure.TIM_Period = arr; //设置自动重装载寄存器周期的值
    TIM_TimeBaseStructure.TIM_Prescaler =psc; //设置时钟频率除数的预分频值
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1; //设置时钟分割
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数
    TIM_TimeBaseInit(TIM6, &TIM_TimeBaseStructure); //②初始化 TIM3
    TIM_ITConfig(TIM6,TIM_IT_Update,ENABLE ); //③允许更新中断
    //中断优先级 NVIC设置
    NVIC_InitStructure.NVIC_IRQChannel = TIM6_IRQn; //TIM3中断
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2; //先占优先级 2级
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; //从优先级 0级
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道被使能
    NVIC_Init(&NVIC_InitStructure); //④初始化 NVIC寄存器
    TIM_Cmd(TIM6, ENABLE); //⑤使能 TIM3 
}

 //定时器 3中断服务程序⑥
void TIM6_IRQHandler(void) //TIM3中断
{ 
    if (TIM_GetITStatus(TIM6, TIM_IT_Update) != RESET) //检查 TIM3更新中断发生与否
    { 
        TIM_ClearITPendingBit(TIM6, TIM_IT_Update ); //清除 TIM3更新中断标志
        Speed_Time_Counter++;
        System_Time_Counter++;
        TIM6_event();
    } 
}

void TIM6_event(void)
{
    if(System_Time_Counter>=System_Routine)
    {
        System_Time_Counter=0;
        //LED1=!LED1;
    }
    if(System_Time_Counter%M2MSerial_HeartBeatRoutine==0)
    {
        DMA_USART2_Tx_Data(OK_Respond,M2MSerial_CmdUnit);
        Flag_USARTHeartBeat=1;
    }
    if(System_Time_Counter%(M2PSerial_TxRoutine_10ms*10)==0)
    {
        Flag_M2PSend=1;
    }
}
